package com.googlecode.jasmincc.framework.namespace;

import java.io.*;
import java.util.*;
import static com.googlecode.ptrace.Ptrace.*;

import com.googlecode.jasmincc.framework.io.*;
import com.googlecode.jasmincc.framework.services.*;

public class Namespace {
	protected String name;

	protected Map<String, File> entities = null;

	protected FilenameFilter fileNameFilter = null;

	protected DirectoryBuilder directoryBuilder = null;

	protected GetGrammarNameByFile getGrammarNameByFile = null;

	public Namespace(String name) {
		this.name = name;
	}

	public File[] getEntities() {
		return (File[]) entities.values().toArray();
	}

	public File getEntity(String name) {
		return entities.get(name);
	}

	public String getName() {
		return this.name;
	}

	public void init() throws Exception {
		reinit();
	}

	protected void reinit() throws Exception {
		ptrace("old: " + name);
		String fileName = CharReplacementService.replace(name, '.', '\\');
		ptrace(name);
		ptrace(fileName);
		entities = new HashMap<String, File>();
		File directory = directoryBuilder.getDirectory(fileName);
		if (directory == null) {
			throw new FileNotFoundException("The namespace [" + fileName + "] cannot be found.");
		}
		if (!directory.isDirectory()) {
			throw new FileNotFoundException("The namespace [" + directory.getAbsolutePath() + "] cannot be represented as a directory.");
		}
		File[] files = directory.listFiles(fileNameFilter);
		for (File file : files) {
			ptrace(file.getName());
			String grammarName = getGrammarNameByFile.getName(file);
			ptrace(grammarName);
			entities.put(grammarName, file);
		}
	}

	public void setDirectoryBuilder(DirectoryBuilder directoryBuilder) {
		this.directoryBuilder = directoryBuilder;
	}

	public void setFileNameFilter(FilenameFilter filenameFilter) {
		this.fileNameFilter = filenameFilter;
	}

	/**
	 * @param getGrammarNameByFile the getGrammarNameByFile to set
	 */
	public void setGetGrammarNameByFile(GetGrammarNameByFile getGrammarNameByFile) {
		this.getGrammarNameByFile = getGrammarNameByFile;
	}

	public void setName(String name) {
		this.name = name;
	}
}
